package cn.fastpay.management.config;

import cn.fastpay.management.security.AuthenticationProviderCustom;

import cn.fastpay.management.security.JwtAuthenticationFilter;
import cn.fastpay.management.security.JwtAuthorizationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;



/**
 * 安全设置累 实现 {@link WebSecurityConfigurerAdapter}
 * @author freewolf
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private AuthenticationProviderCustom authenticationProvider;

    @Value("${setting.security.jwt.expire-time}")
    private Long JWT_EXPIRE_TIME;
    @Value("${setting.security.jwt.secret}")
    private String JWT_SECRET;
    @Value("${setting.security.jwt.header}")
    private String JWT_HEADER;
    @Value("${setting.security.jwt.prefix}")
    private String JWT_PREFIX;
    @Value("${setting.security.jwt.login-url}")
    private String JWT_LOGIN_URL;

    /**
     * HttpSecurity 设置方法 设置允许访问的URL
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.cors().and().csrf().disable().authorizeRequests()
                // 允许
                .antMatchers(HttpMethod.POST, JWT_LOGIN_URL).permitAll()
                .anyRequest().authenticated()
                .and()
                // 注册验证组件
                .addFilter(new JwtAuthenticationFilter(authenticationManager(), JWT_SECRET, JWT_EXPIRE_TIME, JWT_LOGIN_URL))
                // 注册授权组件
                .addFilter(new JwtAuthorizationFilter(authenticationManager(), JWT_SECRET, JWT_HEADER, JWT_PREFIX))
                // Disable 掉 Session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

//    @Override
//    public void configure(AuthenticationManagerBuilder auth) throws Exception {
//        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
//    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authenticationProvider);
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
        return source;
    }

    /**
     * Swagger 所有 API 允许访问
     * @param web
     * @throws Exception
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/v2/api-docs",
                "/configuration/ui",
                "/swagger-resources",
                "/configuration/security",
                "/swagger-ui.html",
                "/webjars/**",
                "/swagger-resources/configuration/ui",
                "/swagge‌​r-ui.html",
                "/swagger-resources/configuration/security");
    }
}
